import * as esriLoader from 'esri-loader'
import PolyfillPromise from 'promise-polyfill'
import Pubsub from 'pubsub-js'
import MapManager from './mapManager'

class bufferAnalysis {
    constructor() {
        this.geosResult = [];
        this.mapView = null;
        this.Graphic = null
        this.Draw = null
        this.Point = null
        this.Polyline = null
        this.Polygon = null
        this.Circle = null
        this.SimpleMarkerSymbol = null
        this.geometryEngine = null
        this.SpatialReference = null
        this.Query = null;
        this.QueryTask = null;
        this.GeometryService = null
        this.BufferParameters = null
        this.ProjectParameters = null
        this.watchUtils = null
    }
    /**
     * @parameter {
     * mapView
     * layername:渲染缓冲的图层名称
     * distance:距离
     * unit :单位"meters"|"feet"|"kilometers"|"miles"|"nautical-miles"|"yards"
     * geo:分析区域
     * urls:[{url:'图层地址',title:'图层名称',displayFieldName:'显示字段',where:'条件（默认为1=1）'}]分析图层集合
     * }
     * @param {*} cbFun 查询完成后调用的返回方法
     */
    initPlotAnalysis(parameter, cbFun) {
        const self = this
        self.mapView = parameter.mapView;
        let layername = parameter.layername;
        let distance = parameter.distance == 0 ? 0.0000001 : parameter.distance;
        let unit = parameter.unit;
        let _geo = parameter.geo;
        let spatialRelationship = "intersects"
        if (parameter.spatialRelationship) {
            spatialRelationship = parameter.spatialRelationship;
        }

        esriLoader.utils.Promise = PolyfillPromise
        esriLoader.loadModules(['esri/Graphic', 'esri/views/draw/Draw', 'esri/geometry/Point', 'esri/geometry/Polyline',
            'esri/geometry/Polygon', 'esri/geometry/Circle', 'esri/symbols/SimpleMarkerSymbol', 'esri/geometry/geometryEngine', 'esri/geometry/SpatialReference',
            'esri/tasks/support/Query', 'esri/tasks/QueryTask',
            'esri/tasks/GeometryService', 'esri/tasks/support/BufferParameters', 'esri/tasks/support/ProjectParameters', 'esri/core/watchUtils'], { url: window.g.ArcGIS_API_URL })
            .then(([Graphic, Draw, Point, Polyline, Polygon, Circle, SimpleMarkerSymbol, geometryEngine, SpatialReference, Query, QueryTask, GeometryService, BufferParameters, ProjectParameters, watchUtils]) => {
                self.Graphic = Graphic
                self.Draw = Draw
                self.Point = Point
                self.Polyline = Polyline
                self.Polygon = Polygon
                self.Circle = Circle
                self.SimpleMarkerSymbol = SimpleMarkerSymbol
                self.geometryEngine = geometryEngine
                self.SpatialReference = SpatialReference
                self.Query = Query
                self.QueryTask = QueryTask
                self.GeometryService = GeometryService
                self.BufferParameters = BufferParameters
                self.ProjectParameters = ProjectParameters
                self.watchUtils = watchUtils
                //缓冲
                const geomSer = new self.GeometryService({
                    url: window.g.MapConfiguration.GeometryServiceURL
                })
                var paramsBuffer = new self.BufferParameters({
                    distances: [distance],
                    unit: unit,
                    spatialRelationship: spatialRelationship,
                    geodesic: true,
                    bufferSpatialReference: self.mapView.spatialReference,//new self.SpatialReference({ wkid: 3857 }),
                    outSpatialReference: self.mapView.spatialReference,
                    geometries: [_geo.geometry]
                });
                geomSer.buffer(paramsBuffer).then(result => {
                    const graphicBuffer = new self.Graphic({
                        id: 'buffer_canbeclear',
                        geometry: result[0],
                        symbol: {
                            type: 'simple-fill',
                            color: [0, 138, 150, 0.2],
                            style: 'solid',
                            outline: {
                                color: [0, 138, 150, 0.5],
                                width: 1
                            }
                        }
                    })
                    MapManager.removeLayer(self.mapView, layername);
                    let layer = MapManager.addLayer({
                        opacity: 1,
                        id: layername,
                    }, 'GraphicsLayer', self.mapView)
                    layer.graphics.addMany([graphicBuffer, _geo])
                    //开始分析
                    let layers = [];
                    if (parameter.urls == null) {
                        for (let k = 0; k < self.mapView.map.layers.items.length; k++) {
                            const element = self.mapView.map.layers.items[k];
                            if (element.url == null || element.url == "") {
                                continue;
                            }
                            layers.push(element);
                        }
                    } else {
                        layers = parameter.urls;
                    }
                    let recordTimes = 0;

                    self.geosResult = []
                    for (let index = 0; index < layers.length; index++) {
                        const elementQ = layers[index];
                        try {
                            const query = new Query();
                            const queryTask = new QueryTask({ url: elementQ.url });
                            query.returnGeometry = true;
                            query.outFields = ["*"];
                            query.where = !!layers.where ? layers.where : "1=1";
                            query.geometry = result[0].extent == null
                                ? result[0]
                                : result[0].extent;
                            queryTask.execute(query).then((response) => {
                                recordTimes += 1;
                                // self.geosResult = []
                                if (response.features.length != 0) {
                                    let response2 = [];
                                    for (let index = 0; index < response.features.length; index++) {
                                        const element = response.features[index];
                                        let in1 = self.geometryEngine.intersects(element.geometry, result[0]);
                                        if (in1) {
                                            response2.push(element);
                                        }
                                    }
                                    response.features = response2;
                                    let resGeo = response;
                                    resGeo.title = elementQ.title;
                                    resGeo.layer = elementQ.layer;
                                    resGeo.displayFieldName = elementQ.labelfieldname ? elementQ.labelfieldname : response.displayFieldName;
                                    self.geosResult.push(resGeo);
                                    if (recordTimes == layers.length) {
                                        //显示结果
                                        if (self.geosResult.length == 0) {
                                            cbFun(null);
                                        } else {
                                            cbFun(self.geosResult);
                                        }
                                    } else {
                                        // cbFun(null);
                                    }
                                } else {
                                    if (recordTimes == layers.length) {
                                        alert("未查询到相关数据");
                                    }
                                }
                            });
                        } catch (error) {
                            recordTimes += 1;
                            continue;
                        }
                    }
                });//得到缓冲图形

            })
            .catch(e => {
                console.error('初始化绘制出错——')
            })
    }
    /**
     * @parameter {
     * mapView
     * layername:渲染缓冲的图层名称
     * distance:距离
     * unit :单位"meters"|"feet"|"kilometers"|"miles"|"nautical-miles"|"yards"
     * geo:分析区域
     * urls:[{url:'图层地址',title:'图层名称',displayFieldName:'显示字段',where:'条件（默认为1=1）'}]分析图层集合
     * }
     * @param {*} cbFun 查询完成后调用的返回方法
     */
    QueryAnalysis(parameter, cbFun) {
        const self = this
        self.mapView = parameter.mapView;
        let layername = parameter.layername;
        let wheres = parameter.wheres;
        // let distance = parameter.distance == 0 ? 0.0000001 : parameter.distance;
        // let unit = parameter.unit;
        // let _geo = parameter.geo;
        // let spatialRelationship = "intersects"
        // if (parameter.spatialRelationship) {
        //     spatialRelationship = parameter.spatialRelationship;
        // }

        esriLoader.utils.Promise = PolyfillPromise
        esriLoader.loadModules(['esri/Graphic', 'esri/views/draw/Draw', 'esri/geometry/Point', 'esri/geometry/Polyline',
            'esri/geometry/Polygon', 'esri/geometry/Circle', 'esri/symbols/SimpleMarkerSymbol', 'esri/geometry/geometryEngine', 'esri/geometry/SpatialReference',
            'esri/tasks/support/Query', 'esri/tasks/QueryTask',
            'esri/tasks/GeometryService', 'esri/tasks/support/BufferParameters', 'esri/tasks/support/ProjectParameters', 'esri/core/watchUtils'], { url: window.g.ArcGIS_API_URL })
            .then(([Graphic, Draw, Point, Polyline, Polygon, Circle, SimpleMarkerSymbol, geometryEngine, SpatialReference, Query, QueryTask, GeometryService, BufferParameters, ProjectParameters, watchUtils]) => {
                self.Graphic = Graphic
                self.Draw = Draw
                self.Point = Point
                self.Polyline = Polyline
                self.Polygon = Polygon
                self.Circle = Circle
                self.SimpleMarkerSymbol = SimpleMarkerSymbol
                self.geometryEngine = geometryEngine
                self.SpatialReference = SpatialReference
                self.Query = Query
                self.QueryTask = QueryTask
                self.GeometryService = GeometryService
                self.BufferParameters = BufferParameters
                self.ProjectParameters = ProjectParameters
                self.watchUtils = watchUtils
                //缓冲
                // const geomSer = new self.GeometryService({
                //     url: window.g.MapConfiguration.GeometryServiceURL
                // })
                // var paramsBuffer = new self.BufferParameters({
                //     // distances: [distance],
                //     // unit: unit,
                //     // spatialRelationship: spatialRelationship,
                //     geodesic: true,
                //     bufferSpatialReference: self.mapView.spatialReference,//new self.SpatialReference({ wkid: 3857 }),
                //     outSpatialReference: self.mapView.spatialReference,
                //     // geometries: [_geo.geometry]
                // });
                // geomSer.buffer(paramsBuffer).then(result => {
                // const graphicBuffer = new self.Graphic({
                //     id: 'buffer_canbeclear',
                //     geometry: result[0],
                //     symbol: {
                //         type: 'simple-fill',
                //         color: [0, 138, 150, 0.2],
                //         style: 'solid',
                //         outline: {
                //             color: [0, 138, 150, 0.5],
                //             width: 1
                //         }
                //     }
                // })
                // MapManager.removeLayer(self.mapView, layername);
                // let layer = MapManager.addLayer({
                //     opacity: 1,
                //     id: layername,
                // }, 'GraphicsLayer', self.mapView)
                // layer.graphics.addMany([graphicBuffer, _geo])
                //开始分析
                let layers = [];
                if (parameter.urls == null) {
                    for (let k = 0; k < self.mapView.map.layers.items.length; k++) {
                        const element = self.mapView.map.layers.items[k];
                        if (element.url == null || element.url == "") {
                            continue;
                        }
                        layers.push(element);
                    }
                } else {
                    layers = parameter.urls;
                }
                let recordTimes = 0;
                self.geosResult = []
                for (let index = 0; index < layers.length; index++) {
                    const elementQ = layers[index];
                    const where = wheres[index]
                    try {
                        const query = new Query();
                        const queryTask = new QueryTask({ url: elementQ.url });
                        query.returnGeometry = true;
                        query.outFields = ["*"];
                        query.where = !!where ? where : "1=1";
                        // query.where = !!layers.where ? layers.where : "1=1";
                        // query.geometry = result[0].extent == null
                        //     ? result[0]
                        //     : result[0].extent;
                        queryTask.execute(query).then((response) => {
                            recordTimes += 1;
                            // self.geosResult = []
                            if (response.features.length != 0) {
                                let response2 = [];
                                for (let index = 0; index < response.features.length; index++) {
                                    const element = response.features[index];
                                    // let in1 = self.geometryEngine.intersects(element.geometry, result[0]);
                                    // if (in1) {
                                    //     response2.push(element);
                                    // }
                                    response2.push(element);
                                }
                                response.features = response2;
                                let resGeo = response;
                                resGeo.title = elementQ.title;
                                resGeo.layer = elementQ.layer;
                                resGeo.displayFieldName = elementQ.labelfieldname;
                                self.geosResult.push(resGeo);
                                if (recordTimes == layers.length) {
                                    //显示结果
                                    if (self.geosResult.length == 0) {
                                        cbFun(null);
                                    } else {
                                        cbFun(self.geosResult);
                                    }
                                } else {
                                    // cbFun(null);
                                }
                            } else {
                                if (recordTimes == layers.length && self.geosResult.length == 0) {
                                    cbFun(null);
                                }
                            }
                        });
                    } catch (error) {
                        recordTimes += 1;
                        continue;
                    }
                }
                // });//得到缓冲图形

            })
            .catch(e => {
                console.error('查询出错——')
            })
    }

}
export default new bufferAnalysis()
